package com.eascs.overdue.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.Format;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.eascs.admin.common.utils.ExcelParser;
import com.eascs.admin.common.utils.ExcelType;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.UrlUtil;
import com.eascs.loan.controller.O2oPaymentsRestController;
import com.eascs.overdue.entity.O2oOverdueFormEntity;
import com.eascs.overdue.service.O2oOverdueReportService;
import com.eascs.overdue.service.O2oOverdueService;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.PaginationRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.web.context.RequestContext;

@Controller
@RequestMapping("/overdueReport")
public class O2oOverdueReportRestController {

	@Autowired
	O2oOverdueReportService o2oOverdueReportService;
	
	@Autowired
	O2oOverdueService o2oOverdueService;
	
	private static Logger log = LoggerFactory.getLogger(O2oOverdueReportRestController.class);

	
	@RequestMapping("/toImport")
	public HtmlRestResult toImport() {
		return HtmlRestResult.popHtmlFragment("overdue/import_overdueReport");
	}

	/**
	 * 预期报表导入 刷新
	 * @param file
	 * @param billCode
	 * @param loanerName
	 * @param idNum
	 * @return
	 */
	@RequestMapping("/uploadExecl")
	public BaseRestResult<String> uploadExcel(@RequestParam(value = "file", required = false) MultipartFile file, String billCode,String loanerName,String idNum) {
		@SuppressWarnings("unused")
		InputStream inputStream = null;
		try {
			inputStream = file.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		ExcelType[] types = new ExcelType[] {//验证excel数据是否正确
				new ExcelType(ExcelType.CELL_TYPE_STRING, true),//1
				new ExcelType(ExcelType.CELL_TYPE_STRING, true),//2
				new ExcelType(ExcelType.CELL_TYPE_NUMERIC, true),//3
				new ExcelType(ExcelType.CELL_TYPE_NUMERIC, true),//4
				new ExcelType(ExcelType.CELL_TYPE_NUMERIC, true),//5
				new ExcelType(ExcelType.CELL_TYPE_NUMERIC, true),//6
				new ExcelType(ExcelType.CELL_TYPE_NUMERIC, true),//7
				new ExcelType(ExcelType.CELL_TYPE_STRING, true),//8
				new ExcelType(ExcelType.CELL_TYPE_NUMERIC, true),//9
				new ExcelType(ExcelType.CELL_TYPE_DATE, true),//10
				new ExcelType(ExcelType.CELL_TYPE_DATE, true),//11
				new ExcelType(ExcelType.CELL_TYPE_STRING, false),//12
		};
		
		long beginTime = System.currentTimeMillis();
		ExcelParser parser = new ExcelParser(types);
		try {
			parser.run(file.getInputStream());
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		List<Object> errorresults = parser.getErrorresults();
		StringBuffer error = new StringBuffer();
		for (int i = 0; i < errorresults.size(); i++) { //如果数据格式有问题，先打出loger 
			//return BaseRestResult.info("导入成功");
			error.append("导入数据有误请检查：错误数据位置为："+(String) errorresults.get(i)+"\r\n");
			log.error("error.excel.read", (String) errorresults.get(i));
		}
		if(error!=null&&StringUtils.isNotBlank(error)){
			return BaseRestResult.warn(error.toString());
		}
		List<List<Object>> results = parser.getResults();  //解析出来的数据
		//循环去查询表插入逾期报表
		
		log.info(new StringBuilder().append("耗时：").append(
				(System.currentTimeMillis() - beginTime)).append(
				",导入记录数：").append(results.size()).append(
				",批量导入级别-导入Excel").toString());
		String result = null;
		try {
			result = o2oOverdueReportService.addList(results);
		} catch (RuntimeException e) {
			return BaseRestResult.info(e.getLocalizedMessage()).andRefresh();
		}
		if(result.equals("success")){
			log.info("逾期导入数据插入临时表中成功。");
			//将临时表中的数据做初步验证之后，修改主表状态，然后更新正式表
			try {
				o2oOverdueReportService.addDealInterim();
			} catch (RuntimeException e) {
				log.error("update o2o_loanapply error message:【{}】", e.getLocalizedMessage());
				return BaseRestResult.info(e.getLocalizedMessage()).andRefresh();
			}
		}else{
			log.info("逾期导入数据插入临时表失败。");
		}
		
		return BaseRestResult.info("导入成功").andRefresh();
	}
	
	@RequestMapping("/download")
	public BaseRestResult<String> dowanload(HttpServletResponse httpServletResponse, HttpServletRequest request) {
		BaseRestResult<String> result = null;
		String file = O2oPaymentsRestController.class.getResource("/excelTemplate/overdueReport.xls").getPath();

		OutputStream os = null;
		try {
			String outfile = "overdueReport.xls";
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(file);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
		return result;
	}
	
	@RequestMapping("/oa")
	public PaginationRestResult findPageOaData(O2oOverdueFormEntity entity) {
		entity.setPageSize(10);
		PageResult<Object[]> pageResult = o2oOverdueService.getPageOverdue(entity);
		String[] oatitles = { "贷款单号", "大区", "经营单位", "借款人姓名", "证件号码", "放款银行", "申请金额(元)", "放款日", "到期日", "拖欠总额(元)", "逾期本金(元)", "逾期利息(元)", "罚息合计(元)", "处置金额(元)", "当前处置状态", "处置时间", "数据来源" };
		SelectDataOption[] selectDataOptions = { null, null, null, null, null, new SelectDataOption("BANKTYPEO2O"), null, null, null, null, null, null, null, null, new SelectDataOption("OTO_OVERDUE_STATUS"), null, null };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, oatitles, UrlUtil.resetParam(RequestContext.getRequestUrlWithQueryString(), "pageOldIndex", ""));
		paginationInfo.setBuildPagingNavigation(true);
		paginationInfo.setFirstRenderColumnIndex(0);
		paginationInfo.setSelectDataOptions(selectDataOptions);
		paginationInfo.setRendTo("#oa_result");
		paginationInfo.setFormats(new Format[] { null, null, null, null, null, null, new DecimalFormat(",##0.00"), null, null, new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00") });
		return PaginationRestResult.buildPaginationRestResult(paginationInfo);
	}

	@RequestMapping("/o2o")
	public PaginationRestResult findPageO2oData(O2oOverdueFormEntity entity) {
		entity.setPageSize(10);
		PageResult<Object[]> pageResult = o2oOverdueService.getPageO2oOverdue(entity);
		String[] oatitles = { "贷款单号","大区","经营单位", "借款人姓名", "证件号码", "放款银行", "申请金额(元)", "放款日", "到期日", "拖欠总额(元)", "逾期本金(元)", "逾期利息(元)", "罚息合计(元)", "处置金额(元)", "当前处置状态", "处置时间", "数据来源" };
		SelectDataOption[] selectDataOptions = { null, null, null, null, null, new SelectDataOption("BANKTYPEO2O"), null, null, null, null, null, null, null, null, new SelectDataOption("OTO_OVERDUE_STATUS"), null, null };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, oatitles,  UrlUtil.resetParam(RequestContext.getRequestUrlWithQueryString(), "pageIndex", ""));
		paginationInfo.setBuildPagingNavigation(true);
		paginationInfo.setFirstRenderColumnIndex(0);
		paginationInfo.setSelectDataOptions(selectDataOptions);
		paginationInfo.setRendTo("#o2o_result");
		paginationInfo.setFormats(new Format[] { null, null, null, null, null, new DecimalFormat(",##0.00"), null, null, new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00") });
		return PaginationRestResult.buildPaginationRestResult(paginationInfo);
	}
	
	/**
	 * @Description:夫妻双方的逾期和代偿信息<br/>
	 * <ul>
	 * <li>工单：</li>
	 * <li>http://tick.o2ojr.eascs.com/ticket/view/loan-10746</li>
	 * </ul>
	 * 
	 * @author CXW
	 * @date 2016年12月28日 下午1:30:27
	 * @version V1.0
	 */
	@RequestMapping("/report")
	public PaginationRestResult findOverReport(O2oOverdueFormEntity entity) {
		entity.setPageSize(10);
		PageResult<Object[]> pageResult = o2oOverdueReportService.findOverReport(entity);
		//String[] oatitles = { "贷款编号","借款人姓名","放款银行","放款金额(元)","到期日期","处置状态","处置时间","拖欠总额(元)","逾期本金(元)","逾期利息(元)","罚息合计(元)","处置金额(元)","统计时间" };
		String[] oatitles = { "贷款单号","借款人姓名","放款银行","放款金额(元)","到期日期","处置状态","处置时间","处置金额(元)","统计时间","贷款状态" };
//		SelectDataOption[] selectDataOptions = { null, null, new SelectDataOption("BANKTYPEO2O"), null, null, new SelectDataOption("OTO_OVERDUE_STATUS"), null, null, null, null, null, null, null};
		SelectDataOption[] selectDataOptions = { null, null, new SelectDataOption("BANKTYPEO2O"), null, null, new SelectDataOption("OTO_OVERDUE_STATUS"), null, null, null, new SelectDataOption("SQZT") };

		PaginationInfo paginationInfo = new PaginationInfo(pageResult, oatitles, UrlUtil.resetParam(RequestContext.getRequestUrlWithQueryString(), "pageIndex", ""));
		paginationInfo.setBuildPagingNavigation(true);
		paginationInfo.setFirstRenderColumnIndex(0);
		paginationInfo.setSelectDataOptions(selectDataOptions);
		paginationInfo.setRendTo("#over_report");
		DecimalFormat decimalFormat = new DecimalFormat(",##0.00");
//		paginationInfo.setFormats(new Format[] { null, null, null, decimalFormat, null, null, null, decimalFormat, decimalFormat, decimalFormat, decimalFormat, decimalFormat, null });
		paginationInfo.setFormats(new Format[] { null, null, null, decimalFormat, null, null, null, decimalFormat, null });
		return PaginationRestResult.buildPaginationRestResult(paginationInfo);
	}
	
	
	/**
	 * @Description:
	 *               <p>
	 *               访问夫妻双方逾期数据
	 *               </p>
	 * @author CXW
	 * @date 2016年12月28日 下午2:01:38
	 * @version V1.0
	 */
	@RequestMapping("/report_view")
	public BaseRestResult<String> report(O2oOverdueFormEntity entity){
		String o2ourl = "/overdueReport/report";
		String idCard = entity.getIdCard() == null ? "" : entity.getIdCard();
		String spouseIdCard = entity.getSpouseIdCard() == null ? "" : entity.getSpouseIdCard();
		o2ourl = UrlUtil.appendUrl(o2ourl, "idCard", idCard);
		o2ourl = UrlUtil.appendUrl(o2ourl, "spouseIdCard", spouseIdCard);
		o2ourl = o2ourl + "&pageIndex=";
		ViewContext.put("report_url", o2ourl);
		return new HtmlRestResult("overdue/spouse_overdue");
	}
	
	@RequestMapping("/overdueLoanPage")
	public PaginationRestResult findOverdueLoanPage(O2oOverdueFormEntity entity) {
		entity.setPageSize(10000);
		String o2ourl = "/overdueReport/overdueLoanPage";
		String idCard = entity.getIdCard() == null ? "" : entity.getIdCard();
		String spouseIdCard = entity.getSpouseIdCard() == null ? "" : entity.getSpouseIdCard();
		o2ourl = UrlUtil.appendUrl(o2ourl, "idCard", idCard);
		o2ourl = UrlUtil.appendUrl(o2ourl, "spouseIdCard", spouseIdCard);
		PageResult<Object[]> pageResult = o2oOverdueService.getO2oOverduePage(entity);
		String titles[] = { "贷款单号", "借款人姓名", "放款银行", "申请金额(元)", "放款日", "到期日", "拖欠总额(元)", "当前处置状态", "处置时间" ,"数椐类型"};
		Format[] formats = new Format[] { null, null, null, new DecimalFormat(",##0.00"), null, null, new DecimalFormat(",##0.00"),null,null };
		SelectDataOption[] selectDataOptions = { null, null, new SelectDataOption("BANKTYPEO2O"), null, null, null, null, new SelectDataOption("O2O_OVERDUE_STATUS"), null,new SelectDataOption("YQ_DATATYPE") };
		PaginationInfo o2oPagingInfo = new PaginationInfo(pageResult, titles, "");
		o2oPagingInfo.setBuildPagingNavigation(false);
		o2oPagingInfo.setFirstRenderColumnIndex(1);
		o2oPagingInfo.setSelectDataOptions(selectDataOptions);
		o2oPagingInfo.setRendTo("#overdue_loan_page");
		o2oPagingInfo.setFormats(formats);
		ViewContext.put("vo", entity);
		ViewContext.put("paginationInfo", o2oPagingInfo);
		return PaginationRestResult.buildPaginationRestResult(o2oPagingInfo);
	}
}
